//
//  PicturePickerViewController.swift
//  照片选择器
//
//  Created by  NorthCity on 15/11/17.
//  Copyright © 2015年  NorthCity. All rights reserved.
//

import UIKit

private let reuseIdentifier = "PicturePickerCell"
private let picturePickerMax = 3
class PicturePickerViewController: UICollectionViewController {
//    照片数组
    lazy var pictures = [UIImage]()
    //   MARK: - 构造函数
     init(){
        let layout:UICollectionViewFlowLayout = PicturePickerLayout()
        super.init(collectionViewLayout:layout)
    }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor.whiteColor()
        // 注册 cell
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    // MARK: 数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  pictures.count + (pictures.count == picturePickerMax ? 0:1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as!PicturePickerCell
        cell.pictureDelegate = self
        cell.picture = (indexPath.item < pictures.count) ? pictures[indexPath.item]:nil
        return cell
    }
    
// MARK:-    照片选择视图布局
    private class PicturePickerLayout:UICollectionViewFlowLayout{
//        构造函数
        private override func prepareLayout() {
            super.prepareLayout()
            let margin = UIScreen.mainScreen().scale * 4
            let count:CGFloat = 4
            
            let w = (UIScreen.mainScreen().bounds.width - margin * (count + 1)) / count
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
//       设置边距
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
    }
}
}
//MARK: -  实现 cell 代理方法
extension PicturePickerViewController:PicturePickerCellDelegate{
  @objc private  func picturePickerCellDidAdd(cell: PicturePickerCell) {
//         1 判断是否允许访问相册
    if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
      return
    }
//         2 访问相册
    let picker = UIImagePickerController()
    presentViewController(picker, animated: true, completion: nil)
//         3  设置代理
        picker.delegate = self
    }
    
  @objc private  func picturePickerCellDidRemove(cell: PicturePickerCell) {
        let index = collectionView!.indexPathForCell(cell)!
    if index.item > pictures.count{
        return
    }
    pictures.removeAtIndex(index.item)
//    collectionView?.deleteItemsAtIndexPaths([index])
    
    collectionView?.reloadData()
    }
}
//MAARK: - 实现相册代理方法
extension PicturePickerViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        print(info)
        let picture = info[UIImagePickerControllerOriginalImage] as! UIImage
        let scalePicture = picture.scaleToWidth(600)
        pictures.append(scalePicture)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}

//MARK:  - 代理协议
@objc
private protocol PicturePickerCellDelegate:NSObjectProtocol {
    optional func picturePickerCellDidAdd(cell:PicturePickerCell)
    optional func picturePickerCellDidRemove(cell:PicturePickerCell)
    
}
//MARK:  - 自定义 cell
//私有类一切属性方法都是私有的
private class PicturePickerCell:UICollectionViewCell{
//    代理属性
    weak var pictureDelegate:PicturePickerCellDelegate?
//    图片属性
  private  var picture:UIImage?{
    didSet{
        addButton.setImage(picture ?? UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        removeButton.hidden = (picture == nil)
    }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    设置布局
    private func setUpUI(){
//        1 添加控件
        addSubview(addButton)
        addSubview(removeButton)
//        2 自动布局
        addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(snp_top)
            make.right.equalTo(snp_right)
        }
        
//        3 添加监听方法
        addButton.addTarget(self, action: "addPhoto", forControlEvents: UIControlEvents.TouchUpInside)
        removeButton.addTarget(self, action: "removePhoto", forControlEvents: UIControlEvents.TouchUpInside)
//        4 图片填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
        
    }
//MARK: - cell懒加载
    private  lazy var addButton:UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil)
    private  lazy var removeButton:UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil)
    
//MARK: - cell 私有方法
 @objc   private func addPhoto(){
         pictureDelegate?.picturePickerCellDidAdd!(self)
    }
 @objc  private func removePhoto(){
         pictureDelegate?.picturePickerCellDidRemove!(self)
    }
    
}








